<template>
    <div>
        <el-form ref="formRef" v-loading="loading" :model="formData" :rules="formRules" label-suffix=":"
                 label-width="120px">

            <div class="grid grid-cols-1 md:grid-cols-2 gap-x-6 gap-y-5">
                <el-form-item class="mb-0" label="权限名称" prop="name">
                    <el-input v-model="formData.name" placeholder="请输入权限名称"/>
                </el-form-item>

                <el-form-item class="mb-0" label="权限标题" prop="title">
                    <el-input v-model="formData.title" placeholder="请输入权限标题"/>
                </el-form-item>
            </div>

            <div class="grid grid-cols-1 md:grid-cols-2 gap-x-6 gap-y-5 mt-5">
                <el-form-item class="mb-0" label="权限类型" prop="type">
                    <el-radio-group v-model="formData.type" @change="handleTypeChange">
                        <el-radio label="F">目录</el-radio>
                        <el-radio label="M">菜单</el-radio>
                        <el-radio label="P">功能</el-radio>
                    </el-radio-group>
                </el-form-item>
            </div>
            <div class="grid grid-cols-1 md:grid-cols-2 gap-x-6 gap-y-5 mt-5">
                <el-form-item class="mb-0" label="排序" prop="sort">
                    <el-input-number v-model="formData.sort" :max="999" :min="0" class="w-full"/>
                </el-form-item>
            </div>

            <div class="grid grid-cols-1 md:grid-cols-2 gap-x-6 gap-y-5 mt-5">
                <el-form-item class="mb-0" label="权限路径" prop="path">
                    <el-input v-model="formData.path" placeholder="/system/user"/>
                </el-form-item>

                <el-form-item v-if="formData.type !== 'F'" class="mb-0" label="组件地址" prop="component">
                    <el-select
                        v-model="formData.component"
                        class="w-full"
                        filterable
                        placeholder="请选择视图组件"
                        @change="handleComponentSelectChange"
                    >
                        <el-option-group label="视图组件">
                            <el-option
                                v-for="module in viewModules"
                                :key="module.name"
                                :label="handleModuleName(module.name)"
                                :value="handleModuleName(module.name)"
                            >
                                <template #default>{{ module.name }}</template>
                            </el-option>
                        </el-option-group>
                    </el-select>
                </el-form-item>
            </div>

            <div class="mt-5">
                <el-form-item class="w-full mb-0" label="API路径" prop="apiPath">
                    <el-input v-model="formData.apiPath" placeholder="/system/user/list"/>
                </el-form-item>
            </div>

            <div class="mt-5">
                <el-form-item class="w-full mb-0" label="权限标识" prop="perms">
                    <el-input v-model="formData.perms" placeholder="例如：system:user:list"/>
                </el-form-item>
            </div>

            <div class="grid grid-cols-1 md:grid-cols-2 gap-x-6 gap-y-5 mt-5">
                <el-form-item class="mb-0" label="状态" prop="status">
                    <el-radio-group v-model="formData.status">
                        <el-radio :label="1">启用</el-radio>
                        <el-radio :label="0">停用</el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item class="mb-0" label="隐藏" prop="hidden">
                    <el-radio-group v-model="formData.hidden">
                        <el-radio :label="0">显示</el-radio>
                        <el-radio :label="1">隐藏</el-radio>
                    </el-radio-group>
                </el-form-item>
            </div>

            <!-- === 第七行：父级权限（复杂下拉，建议独占整行）=== -->
            <div class="mt-5">
                <el-form-item class="w-full" label="父级权限" prop="parentId">
                    <el-select
                        v-model="formData.parentId"
                        class="w-full"
                        filterable
                        placeholder="请选择父级权限"
                        @change="handleParentChange"
                    >
                        <el-option :value="0" label="根目录"/>
                        <el-option
                            v-for="perm in perms"
                            :key="perm.id"
                            :label="perm.title"
                            :value="perm.id"
                        >
                            <template #default>
                                <span class="float-left">{{ perm.title }}</span>
                                <span class="float-right text-gray-500 text-sm">{{ perm.name }}</span>
                            </template>
                        </el-option>
                    </el-select>
                </el-form-item>
            </div>

            <!-- === 操作按钮 === -->
            <div class="mt-8 flex space-x-3">
                <el-form-item>
                    <el-button type="primary" @click="submit">提交</el-button>
                    <el-button @click="cancel">取消</el-button>
                </el-form-item>
            </div>
        </el-form>
    </div>
</template>

<script setup>
import {ref, unref} from "vue";
import {useRouter} from "vue-router";
import instance from "@/api/request.js";

const emit = defineEmits(["submit", "cancel"])
const props = defineProps(["data"])

const formRef = ref()


const formData = reactive({
    type: 'M',
    parentId: 0,
    status: 1,
    sort: 0,
    hidden: 0
})
const perms = ref([])

const formRules = reactive({
    name: [
        {required: true, message: '请输入权限名称', trigger: 'blur'},
        {min: 2, max: 32, message: '长度在 2 到 32 个字符之间', trigger: 'blur'}
    ],
    title: [
        {required: true, message: '请输入权限标题', trigger: 'blur'},
        {min: 2, max: 32, message: '长度在 2 到 32 个字符之间', trigger: 'blur'}
    ],
    type: [
        {required: true, message: '请选择权限类型', trigger: 'change'}
    ],
    component: [
        // 只有当 type 是 'M' 或 'P' 时才需要组件地址
        {
            validator: (rule, value, callback) => {
                const {type} = formData;
                if (type === 'M' || type === 'P') {
                    if (!value || !value.trim()) {
                        return callback(new Error('请选择组件地址'));
                    }
                    return callback();
                }
                callback(); // 不需要时不校验
            },
            trigger: 'change'
        }
    ],
    path: [
        {required: true, message: '请输入权限路径', trigger: 'blur'},
        {
            pattern: /^[a-zA-Z0-9/_\-:~.]+$/,
            message: '路径只能包含字母、数字、斜杠、横线、下划线等合法路径字符',
            trigger: 'blur'
        }
    ],
    apiPath: [
        // 非必填但格式正确（可选）
        {
            pattern: /^\/[a-zA-Z0-9/_\-{}:.]*$/,
            message: 'API路径应以/开头，支持REST风格占位符如{id}',
            trigger: 'blur'
        }
    ],
    perms: [
        {required: true, message: '请输入权限标识', trigger: 'blur'},
        {pattern: /^[a-zA-Z0-9:_-]+$/, message: '权限标识只允许字母、数字、冒号、下划线和横线', trigger: 'blur'}
    ],
    sort: [
        {required: true, message: '请输入排序值', trigger: 'blur'},
        {type: 'number', min: 0, max: 999, message: '排序必须是 0-999 之间的数字', trigger: 'blur'}
    ],
    status: [
        {required: true, message: '请选择状态', trigger: 'change'}
    ],
    hidden: [
        {required: true, message: '请选择是否隐藏', trigger: 'change'}
    ],
    parentId: [
        {required: true, message: '请选择父级权限', trigger: 'change'},
        {type: 'number', message: '父级权限必须是一个有效编号', trigger: 'change'}
    ]
});

async function submit() {
    let validateState = await formRef.value.validate()
        .then((res) => {
            return res;
        });
    if (validateState) {
        instance.post("/permission/insert", {...unref(formData)}).then(
            res => {
                if (res.code === 200) {
                    ElMessage.success(res.message || "添加完成")
                    // emit('submit', formData)
                }else {
                    ElMessage.error(res.data)
                }
            }
        )
    }
}

function cancel() {
    // formRef.value.resetFields()
    emit('cancel')
}

const router = useRouter()
const viewModules = ref({})
const loading = ref(false)
onMounted(async () => {
    loading.value = true;
    viewModules.value = getCurrentInstance().proxy.$modules;
    await fetchPermList();
});

const handleTypeChange = (val) => {
    if (val === 'F') {
        formData.component = null
    }

}

const handleModuleName = (moduleName) => {
    return moduleName.replace(/^\/src\/views\/|\/src\/components\/|\.vue$/g, '');
}

const handleComponentSelectChange = () => {
    formData.path = "/" + formData.component;
}

const handleParentChange = (val) => {
    console.log(val)
}

async function fetchPermList() {
    await instance.post("/permission/menu", {name: ''}).then(res => {
        perms.value = res.data
        loading.value = false;
    })
}

</script>